import { read, utils } from 'xlsx';


interface President {
    Name: string;
    Index: number;
}

const debounce = (func, delay) => {
    let timer: null | NodeJS.Timeout = null;
    return () => {
        clearTimeout(timer!)
        timer = setTimeout(function(){
            func()
        }, delay)
    }
}

type ReadExcel<T = any> = (url: string) => Promise<T>
const readExcel: ReadExcel = async (url: string) => {
    const f = await (await fetch(url)).arrayBuffer();
    const wb = read(f);
    const data = utils.sheet_to_json<President>(wb.Sheets[wb.SheetNames[0]]);
    return data
}


// 下载
const downloadDocument = (content: string, documentName: string) => {
    let aTag = document.createElement('a')
    let blob = new Blob([content])
    aTag.download = documentName
    aTag.href = URL.createObjectURL(blob)
    aTag.click()
    URL.revokeObjectURL(aTag.href)
}

// 处理字符串
const solveSpecificStr = (strList: string) => {
    // '-1_1_47_47'
    const res: any = [];
    const target = strList.replace('[', '').replace(']', '').replaceAll('\'', '').replaceAll(' ', '').split(',')
    
    for(const str of target) {
        if (str == '0') {
            res.push([ 0, 0 ]);
        } else {
            const arr = JSON.parse(JSON.stringify(str.split('_'))).map((s) => Number(s.trim()));
            res.push([ arr[2] * arr[0], arr[3] * arr[1] ])
        }
    }
    const real: any = [];
    const imag: any = [];

    res.forEach(([r, i]) => {
        real.push(r);
        imag.push(i);
    })
    return [ real, imag ];
}

const utf8ToString = (str: string) => {
    return unescape(str .replace(/&#x/g, '%u').replace(/;/g, ''));
}

export {
    debounce,
    downloadDocument,
    readExcel,
    solveSpecificStr,
    utf8ToString,
}